/*
 * (C)2012 Exlu Corporation. All rights reserved.
 * 文件名 : cn.exlu.wea.io.directory.LpDiretory.java
 * 注意事項   :
 */
package cn.exlu.wea.io.directory;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Mark 
 * @version 1.0.0
 * @date 2014-5-11
 * @fileName LpDiretory.java
 */
public class LpDirectory extends File {

    /**   */
    private static final long serialVersionUID = 1L;

    /**
     * @param pathname
     */
    public LpDirectory(String pathname) {
        super(pathname);

        if (DirectoryManager.isDirecotry(this)) {
            return;
        }

        this.mkdirs();
    }

    /**
     * 创建子目录，若存在，则直接返回。
     * @param directoryPath
     * @return
     */
    public LpDirectory CreateDirectory(String directoryPath) {

        int firstChar = directoryPath.charAt(0);
        String direcFullPath = "";

        if (firstChar == File.separatorChar) {
            direcFullPath = this.getPath() + directoryPath;
        } else {
            direcFullPath = this.getPath() + File.separatorChar + directoryPath;
        }

        LpDirectory file = new LpDirectory(direcFullPath);

        if (DirectoryManager.isDirecotry(file)) {
            return file;
        }

        file.mkdirs();

        return file;
    }

    /**
     * 从指定目录下查找文件，若找到第一个，则返回。
     * @param directory 目录
     * @return 若找到则返回，否则返回NULL
     */
    public File findFile(String fileName) {

        return findFile(this, fileName);

    }

    private File findFile(File file, String fileName) {
        File[] filesInDirectory = file.listFiles();

        for (File fileInDct : filesInDirectory) {
            if (FileManager.isFile(fileInDct)) {
                if (fileInDct.getName().equalsIgnoreCase(fileName)) {
                    return fileInDct;
                }
            } else if (DirectoryManager.isDirecotry(fileInDct)) {
                File fileTemp = findFile(fileInDct, fileName);
                if (fileTemp == null) {
                    continue;
                } else {
                    return fileTemp;
                }
            }
        }

        return null;
    }

    public List<File> findFiles(String regexName) {
        List<File> listFile = new ArrayList<File>();
        findFiles(listFile, this, regexName);

        return listFile;
    }

    private void findFiles(List<File> fileList, File dirc, String regexName) {

        fileList.addAll(Arrays.asList(dirc.listFiles(new LpFileNameFilter(regexName))));

        File[] filesInDirectory = dirc.listFiles();

        for (File fileInDct : filesInDirectory) {
            if (DirectoryManager.isDirecotry(fileInDct)) {
                findFiles(fileList, fileInDct, regexName);
            }
        }
    }

}
